<?php


namespace app\common\mail;

class PHPMailer
{
	public static function send($Config, $Subject, $Body, $ToAddress, $Files = [])
	{
		if (empty($Config["Host"]) || empty($Config["Port"]) || empty($Config["Username"]) || empty($Config["Password"]) || empty($Config["From"]) || empty($Config["FromName"])) {
			return "邮箱必要参数未配置";
		}
		$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
		try {
			$mail->SMTPDebug = \PHPMailer\PHPMailer\SMTP::DEBUG_OFF;
			$mail->IsSMTP();
			$mail->CharSet = $Config["CharSet"] ?? "UTF-8";
			$mail->Host = $Config["Host"];
			$mail->SMTPSecure = $Config["SMTPSecure"] ?? \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
			$mail->Port = $Config["Port"];
			$mail->SMTPAuth = $Config["SMTPAuth"] ?? true;
			$mail->Username = $Config["Username"];
			$mail->Password = $Config["Password"];
			$mail->From = $Config["From"];
			$mail->FromName = $Config["FromName"];
			$email_addr = $ToAddress;
			$mail->AddAddress($email_addr, substr($email_addr, 0, strpos($email_addr, "@")));
			$mail->AddReplyTo(empty($Config["ReplyAddress"]) ? $mail->From : $Config["ReplyAddress"], empty($Config["ReplyAddressName"]) ? $mail->FromName : $Config["ReplyAddressName"]);
			$mail->IsHTML(true);
			$mail->Subject = $Subject;
			$mail->Body = $Body;
			$mail->AltBody = $Config["AltBody"] ?? "";
			foreach ($Files as $file) {
				if (is_array($file) && file_exists($file["path"])) {
					$mail->AddAttachment($file["path"], $file["name"] ?? "");
				} else {
					if (file_exists($file)) {
						$mail->AddAttachment($file);
					}
				}
			}
			$mail->send();
			return true;
		} catch (\PHPMailer\PHPMailer\Exception $e) {
			return $mail->ErrorInfo;
		}
	}
	public static function test()
	{
		return self::send(["CharSet" => "UTF-8", "Host" => "smtp.qq.com", "SMTPSecure" => "ssl", "Port" => 465, "SMTPAuth" => true, "Username" => "775294852@qq.com", "From" => "775294852@qq.com", "FromName" => "爱码科技1", "Password" => "vnftqsguxfwrbfge", "ReplyAddress" => "775294852@qq.com", "ReplyAddressName" => "回复地址名称", "AltBody" => "测试附加内容"], "标题", "内容", "468064@qq.com", "爱码科技2");
	}
}